package com.view.comp.ImageCroping.ui
{
	import flash.display.BitmapData;
	import flash.utils.ByteArray;
	
	import mx.core.UIComponent;
	import mx.graphics.codec.JPEGEncoder;
	import mx.utils.Base64Encoder;
	
	public class ImageEncoder
	{
		public function ImageEncoder()
		{
			
		}
		
		/**
		 * Reads and returns the ByteArray data from a UI Component.
		 * Then parses it as a string
		 * 
		 * @param source
		 * @return String
		 */		
		public static function getJPGBinaryString(source:UIComponent):String
		{
			var base64Encoder:Base64Encoder = new Base64Encoder();
			var byteArrayData:ByteArray = ImageEncoder.getJPGByteArrayData(source);
			base64Encoder.encodeBytes(byteArrayData);
			var encodedImageString:String = base64Encoder.flush();			
			return encodedImageString;
		}
		
		/**
		 * Reads and returns the ByteArray data from a UI Component
		 * 
		 * @param source
		 * @return ByteArray
		 */		
		public static function getJPGByteArrayData(source:UIComponent):ByteArray
		{
			var bd:BitmapData = new BitmapData(source.width, source.height); 
			bd.draw(source, null, null, null, null, true);
			
			var jpgEncoder:JPEGEncoder = new JPEGEncoder(100);
			var byteArrayData:ByteArray = jpgEncoder.encode(bd);
			
			return byteArrayData;
		}

	}
}